package com.rtsapp.server.domain.dao;

import com.rtsapp.server.domain.EntityBuilder;
import com.rtsapp.server.domain.entity.TestPlayerEntity;
import com.rtsapp.server.domain.mysql.sql.MySQLPreparedStatement;
import com.rtsapp.server.domain.mysql.sql.MySQLResultSetHandler;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by admin on 15-10-9.
 */
public class PlayerDaoImpl extends  PlayerDao{





    public TestPlayerEntity get( java.lang.Integer id ) {
        com.rtsapp.server.domain.mysql.sql.DatabaseWorkerPool db = getReadPool();
        MySQLPreparedStatement stmt = db.getPreparedStatement("PlayerDao_get_Integer");
        stmt.setParams(new Object[]{id});
        com.rtsapp.server.domain.dao.PlayerDao$ResultHandler handler = new com.rtsapp.server.domain.dao.PlayerDao$ResultHandler();
        db.query(stmt, handler);
        if (handler.getEntityList().size() > 0) {
            return null;
        } else {
            return handler.getEntityList().get(0);
        }
    }

    public void update( TestPlayerEntity entity ){
        com.rtsapp.server.domain.mysql.sql.DatabaseWorkerPool db = getWritePool(  );
        MySQLPreparedStatement stmt =  db.getPreparedStatement( "PlayerDao_update_PlayerEntity" );
        stmt.setParams( new Object[]{ entity.getUserName( ), entity.getPlayerId( )} );
        db.execute( stmt );
    }
    public void insert( TestPlayerEntity entity ){
        com.rtsapp.server.domain.mysql.sql.DatabaseWorkerPool db = getWritePool(  );
        MySQLPreparedStatement stmt =  db.getPreparedStatement( "PlayerDao_insert_PlayerEntity" );
        stmt.setParams( new Object[]{entity.getPlayerId( ),entity.getUserName( )} );
        db.execute( stmt );

    }
    public boolean innerPrepareStatement( com.rtsapp.server.domain.mysql.sql.DatabaseWorkerPool db ) {
        if( !db.prepareStatement( "PlayerDao_get_Integer", " select playerId,userName from PlayerEntity where playerId= ? " ) ){ return false; }
        if( !db.prepareStatement( "PlayerDao_update_PlayerEntity"," update PlayerEntity set userName=?  where playerId= ? " ) ){ return false; }
        if( !db.prepareStatement( "PlayerDao_insert_PlayerEntity", "insert into PlayerEntity( playerId,userName ) values ( ?,? ) " ) ){ return false; }
        return true;
    }

}


 class PlayerDao$ResultHandler implements MySQLResultSetHandler{

    private List<TestPlayerEntity> entityList ;

    public List<TestPlayerEntity> getEntityList(){
        return entityList;
    }

    public void doResultSet(ResultSet rs) {
        try {
            while ( rs.next() ) {
                TestPlayerEntity entity = EntityBuilder.newEntity( TestPlayerEntity.class );
                entity.setPlayerId(rs.getInt(1));
                entity.setUserName(rs.getString(2));
                entityList.add( entity );
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}